<!DOCTYPE html>
<html class="x-admin-sm" lang="en"
      xmlns:th="https://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi"/>
    <link rel="stylesheet" th:href="@{/assets/admin/css/font.css}">
    <link rel="stylesheet" th:href="@{/assets/admin/css/xadmin.css}">
    <script th:src="@{/assets/admin/lib/layui/layui.js}" charset="utf-8"></script>
    <script type="text/javascript" th:src="@{/assets/admin/js/xadmin.js}"></script>
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>
<div class="x-nav">
            <span class="layui-breadcrumb">
                <a href="">首页</a>
                <a href="">演示</a>
                <a>
                    <cite>导航元素</cite></a>
            </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
       onclick="location.reload()" title="刷新">
        <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i>
    </a>
</div>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body ">
                    <form class="layui-form" action="" lay-filter="query_user_form">
                        <div class="layui-inline layui-show-xs-block">
                            <input class="layui-input" autocomplete="off" placeholder="开始日" name="start" id="start">
                        </div>
                        <div class="layui-inline layui-show-xs-block">
                            <input class="layui-input" autocomplete="off" placeholder="截止日" name="end" id="end"></div>
                        <div class="layui-inline layui-show-xs-block">
                            <input type="text" name="username" placeholder="请输入用户名" autocomplete="off"
                                   class="layui-input" id="username"></div>
                        <div class="layui-inline layui-show-xs-block">
                            <button class="layui-btn" lay-submit lay-filter="sreach">
                                <i class="layui-icon">&#xe615;</i>查询</button>
                        </div>
                    </form>
                </div>
                <div class="layui-card-body ">
                    <button class="layui-btn layui-btn-warm" onclick="openAddUser()">
                        <i class="layui-icon">&#xe642;</i>新增用户
                    </button>
                    <button class="layui-btn" onclick="disableUser()">
                        <i class="layui-icon">&#xe69c;</i>禁用
                    </button>
                    <table class="layui-table" lay-filter="user-table" id="table1">
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script th:src="@{/assets/admin/js/jquery.min.js}"></script>
<script th:replace="systemCommon/HarinCommon :: commonJs"></script>
<script type="text/html" id="switchStatus">
    <!--这里的checked的状态只是演示-->
    <input type = "checkbox" name = "status" value = "{{ d.id }}" lay-skin = "switch"lay-text = "正常|停用" lay-filter = "" {{ d.status == 1 ? 'checked':'' }}>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="resetPassword">修改密码</a>
    <shiro:hasRole name="admin">
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="roleConfig">角色分配</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </shiro:hasRole>
</script>

<script>
    let userTable = null;
    $(function () {
    });

    layui.use(['jquery','laydate', 'table', 'form'],
        function () {
            laydate = layui.laydate;
            table = layui.table;
            form = layui.form;
            $ = layui.jquery;

            table.on('edit(user-table)', function (obj) { //里面的值是table的lay-filter
                let value = obj.value; //得到修改后的值
                data = obj.data; //得到所在行所有键值
                field = obj.field; //得到字段
                layer.msg('[' + field + ': ' + data.id + '] ' + field + ' 字段更改为：' + value);
                //失去焦点
                $(this).blur();
            });

            //执行一个laydate实例
            laydate.render({
                elem: '#start' //指定元素
            });

            //执行一个laydate实例
            laydate.render({
                elem: '#end' //指定元素
            });

            //第一个实例
            userTable = table.render({
                elem: '#table1',
                url: '/user/getUserList', //数据接口
                id:"user_table_id",
                method: "get",
                where: {     //请求参数
                    "s_date": $("#start").val(),
                    "e_date": $("#end").val(),
                    "username":$("#username").val()
                },
                parseData: function (res) { //res 即为原始返回的数据
                    var data = res.result;
                    //console.log(data.records);
                    //console.log(typeof data.records);
                    return {
                        "code": res.code, //解析接口状态
                        // "msg": res.message, //解析提示文本
                        "count": data.total, //解析数据长度
                        "data": data.records //解析数据列表
                    };
                },
                response: {//重新定义规则
                    //statusName: 'status', //规定数据状态的字段名称，默认：code
                    statusCode: 200, //规定成功的状态码，默认：0
                    //msgName: 'hint', //规定状态信息的字段名称，默认：msg
                    //countName: 'total', //规定数据总数的字段名称，默认：count
                    //dataName: 'rows' //规定数据列表的字段名称，默认：data
                },
                page: true, //开启分页
                limits: [10, 20, 50],//可选条目数
                toolbar: true,//若需要“列显示隐藏”、“导出”、“打印”等功能，则必须开启该参数
                loading: true, //家在动画
                cols: [
                    [ //表头
                        {type: 'checkbox', fixed: 'left'},
                        {field: 'id', title: 'ID', sort: true, fixed: 'left', width: 80, unresize: true},
                        {field: 'name', title: '姓名', fixed: 'left',width:100},
                        {field: 'username', title: '工号',width:150},
                        {field: 'sex', title: '性别', width: 80, unresize: true, sort: true },
                        {field: 'state', title: '状态', templet: '#switchStatus', width: 95,unresize: true},
                        {field: 'createTime', title: '创建时间',width:145,sort: true,templet : "<div>{{layui.util.toDateString(d.createTime, 'yyyy年MM月dd日 HH:mm:ss')}}</div>"},
                        {field: 'lastLoginTime', title: '最后登录时间', sort: true,width: 150,templet : "<div>{{layui.util.toDateString(d.lastLoginTime, 'yyyy年MM月dd日 HH:mm:ss')}}</div>"},
                        {field: 'lastLoginIp', title: '最后登录IP',width: 120},
                        {field: 'operation', title:'操作', toolbar: '#barDemo',fixed: 'right',width:300}
                    ]
                ]
            });

            //必须使用单引号。过分坑啊！！！！
            form.on('submit(sreach)', function (data) {
                userTable.reload({
                    where: {
                        "s_date": data.field.start,
                        "e_date": data.field.end,
                        "username": data.field.username
                    },
                    page:{
                        curr:1
                    }
                });
                return false;
            });
            //监听行工具事件  这个user-table是指，<table> 属性lay-filter = 'user-table'
            table.on('tool(user-table)', function (obj) {
                //当前行的数据
                let data = obj.data;
                //删除
                if(obj.event === "del"){
                    layer.confirm("确定删除吗？",function(index){
                        $.ajax({
                            url: "/user/deleteUserById",
                            type: "DELETE",
                            data: {"userId": data.id},
                            dataType: "json",
                            success: function (data) {
                                refreshData();
                                if (data.code == 200) {
                                    layer.alert(data.message, {icon: 6}, function (iIndex) {
                                        layer.close(iIndex);
                                    });
                                } else {
                                    layer.alert(data.message, {icon: 5}, function (iIndex) {
                                        layer.close(iIndex);
                                    });
                                }
                            }
                        });
                        layer.close(index);
                    });
                }//编辑
                else if(obj.event === "edit"){
                    openLayer("编辑用户信息","/system/userEditUI?userId="+data.id,null,null,false,refreshData());
                }//角色分配
                else if(obj.event ===  "roleConfig"){
                    openLayer("编辑用户所属角色","/system/rolePermission?userId="+data.id,null,null,false,null);
                }else if(obj.event === "resetPassword"){

                    layer.prompt({
                        formType: 0,
                        value: '',
                        title: '请输入新密码',
                        btn: ['修改','取消'],
                        btnAlign: 'c'
                    }, function(value,index){
                        layer.close(index);
                        $.ajax({
                            url: "/user/resetPassword",
                            type: 'POST',
                            data: {
                                userId: data.id,
                                password : value
                            },
                            success: function (data) {
                                if (data.code == 200) {
                                    layer.alert(data.message, {icon: 6}, function (iIndex) {
                                        layer.close(iIndex);
                                    });
                                } else {
                                    layer.alert(data.message, {icon: 5}, function (iIndex) {
                                        layer.close(iIndex);
                                    });
                                }
                            }
                        });
                    },function (value,index) {

                    });
                }
            });

    //点击行checkbox选中
    $(document).on("click", ".layui-table-body table.layui-table tbody tr", function() {
        var index = $(this).attr('data-index');
        var tableBox = $(this).parents('.layui-table-box');
        //存在固定列
        if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length > 0) {
            tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
        } else {
            tableDiv = tableBox.find(".layui-table-body.layui-table-main");
        }
        var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
        if (checkCell.length > 0) {
            checkCell.click();
        }
    });

    $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function(e) {
        e.stopPropagation();
    });

    //监听复选框事件，被选中的行高亮显示
    table.on('checkbox(user-table)', function (obj) {
        if (obj.checked == true && obj.type == 'all') {
            //点击全选
            $('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click');
        } else if (obj.checked == false && obj.type == 'all') {
            //点击全不选
            $('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click');
        } else if (obj.checked == true && obj.type == 'one') {
            //点击单行
            if (obj.checked == true) {
                obj.tr.addClass('layui-table-click');
            } else {
                obj.tr.removeClass('layui-table-click');
            }
        } else if (obj.checked == false && obj.type == 'one') {
            //点击全选之后点击单行
            if (obj.tr.hasClass('layui-table-click')) {
                obj.tr.removeClass('layui-table-click');
            }
        }
    });

});
    function refreshData(page) {
        if(isEmpty(page)){
            page = $(".layui-laypage-em").next().html();
        }
        //获取form表单的数据，query_user_form 是 <form lay-filter="query_user_form">
        var data = form.val("query_user_form");
        userTable.reload({
            page: {
                curr: page  //主要代码行
            },
            where: {
                "s_date": data.start,
                "e_date": data.end,
                "username": data.username
            }
        });
    }
    function openAddUser(){
        openLayer('新增用户','/system/userEditUI',null,null,false,refreshData());
    }
    function disableUser(){
        let datas = table.checkStatus("user_table_id").data;
        if(datas.length == 0){
            layer.msg("请勾选一个需要禁用的用户");
        }else if(datas.length == 1) {
            // let ids = new Array();
            // $.each(datas,function(index,item) {
            //     if (ids.indexOf(item.id) < 0) {
            //         ids.push(item.id);
            //     }
            // });
            layer.confirm("确定禁用 \'"+datas[0].username+"\'吗？",function(index) {
                $.ajax({
                    url: "/user/disableUser",
                    type: "post",
                    data: {"id": datas[0].id},
                    success: function (data) {
                        if (data.code == 200) {
                            layer.alert(data.message, {icon: 6}, function (index2) {
                                //关闭当前frame
                                layer.close(index);
                            });
                            refreshData(null);
                        } else {
                            layer.alert(data.message, {icon: 5}, function (index2) {
                                //关闭当前frame
                                layer.close(index);
                            });
                        }
                    }
                });
            });
        }else{
            layer.open({
                title:"错误",
                content:"每次禁用只能勾选一位用户",
                anim:6,
                icon: 5
            });
        }
    }
</script>
</html>